package com.zhongyu.item.consumer.service.Impl;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.zhongyu.comm.vo.PageResult;
import com.zhongyu.item.consumer.elastic.ItemDoc;
import com.zhongyu.item.consumer.elastic.ItemDocRepository;
import com.zhongyu.item.consumer.elastic.ItemDto;
import com.zhongyu.item.consumer.elastic.ItemResult;
import com.zhongyu.item.consumer.service.ItemDocService;
import org.apache.lucene.queryparser.xml.builders.BooleanQueryBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.mapping.callback.EntityCallback;
import org.springframework.data.mapping.callback.EntityCallbacks;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service("ItemDocService")
public class ItemDocServicelmpl implements ItemDocService {
    //   @Resource
    // private ItemDocRepository itemDocRepository;

    //  @Resource
    // private RestHighLevelClient restHighLevelClient;

    @Resource
    private  ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public PageResult queryItemList(ItemDto itemDto) {
        PageResult pageResult=new PageResult();
        pageResult.setCurrentPage(itemDto.getCurrentPage());
        pageResult.setPageSize(itemDto.getPageSize());


        BoolQueryBuilder booleanQueryBuilder=new BoolQueryBuilder();
        if (!StringUtils.isEmpty(itemDto.getKeyword())){
            booleanQueryBuilder.must(new MatchQueryBuilder("itemName",itemDto.getKeyword()));
            booleanQueryBuilder.should(new MatchQueryBuilder("abstractMessage",itemDto.getKeyword()));
        }
        if (itemDto.getAreaId()!=0) {
            booleanQueryBuilder.must(new TermQueryBuilder("areaId", itemDto.getAreaId()));
        }
        if (itemDto.getItemTypeId1()!=0){
            booleanQueryBuilder.must(new TermQueryBuilder("itemTypeId1",itemDto.getItemTypeId1()));
        }
        if (itemDto.getItemTypeId2()!=0){
            booleanQueryBuilder.must(new TermQueryBuilder("itemTypeId2",itemDto.getItemTypeId2()));
        }
        if (!StringUtils.isEmpty(itemDto.getEndTime())){
            booleanQueryBuilder.must(new RangeQueryBuilder("startTime").gte(itemDto.getStartTime()));
            booleanQueryBuilder.must(new RangeQueryBuilder("endTime").lte(itemDto.getEndTime()));
        }

        Query query=new NativeSearchQuery(booleanQueryBuilder);
        Sort sort=Sort.by(Sort.Order.desc("isRecommend"));
        switch (itemDto.getSort()){
            case "recommend":
                sort=Sort.by(Sort.Order.desc("isRecommend"));
                break;
            case "recentShow":
                sort=Sort.by(Sort.Order.desc("startTime"));
                break;
            case "recentSell":
                sort=Sort.by(Sort.Order.asc("createdTime"));
                break;
        }
        //第一个参数代表从0开始的页码
        Pageable pageable= PageRequest.of(itemDto.getCurrentPage()-1,itemDto.getPageSize(),sort);
        query.setPageable(pageable);


        HighlightBuilder highlightBuilder=new HighlightBuilder().field("itemName");
        highlightBuilder.field("abstractMessage");
        highlightBuilder.preTags("<em style='color:red'>").postTags("</em>");
        HighlightQuery highlightQuery=new HighlightQuery(highlightBuilder);
        query.setHighlightQuery(highlightQuery);

        SearchHits<ItemDoc> hits= elasticsearchRestTemplate.search(query,ItemDoc.class);
        long total=hits.getTotalHits();
        long pageSize=itemDto.getPageSize();
        if(total%pageSize==0){
            pageResult.setPageCount(total/pageSize);
        }else{
            pageResult.setPageCount(total/pageSize+1);
        }
        pageResult.setTotal(total);


        List<ItemResult> rows=  hits.getSearchHits().stream().map(hit->{
            ItemResult itemResult=new ItemResult();
            ItemDoc itemDoc=hit.getContent();
            BeanUtils.copyProperties(itemDoc,itemResult);
            List<String> itemNameList=hit.getHighlightField("itemName");
            if(itemNameList!=null&&itemNameList.size()>0) {
                String itemName = itemNameList .get(0);
                itemResult.setItemName(itemName);
            }
            List<String> abstractMessageList=hit.getHighlightField("abstractMessage");
            if(abstractMessageList!=null&&abstractMessageList.size()>0) {
                String  abstractMessage= abstractMessageList .get(0);
                itemResult.setAbstractMessage(abstractMessage);
            }
            return itemResult;
        }).collect(Collectors.toList());

        pageResult.setRows(rows);

        return pageResult;
    }
}
